<template>
  <div style="height: 6vh;background-color:#fff;padding: 10px 20px;">
    <span style="line-height:60px;font-size:20px;">健康咨询管理</span>
    <el-button type="primary" style="float: right;margin-top: 10px;"
               @click="beforeAddUser">新建文章</el-button>
  </div>
<!--   新建用户弹窗 -->
<!--   :before-close="handleClose" 在弹窗关闭前先调用handleClose方法来处理弹窗的关闭问题-->
<!--   避免点击弹窗外部也能关闭弹窗-->
  <el-dialog
      :title="dialogTitle"
      style="width: 70%;padding: 40px; height: 80%"
      v-model="dialogVisible"
      :before-close="handleClose"
  >
    <!--  <div>-->
    <!--    <button @click="getHtml">获取 html</button>-->
    <!--  </div>-->
    <div style="border: 1px solid #ccc">
      <!-- 工具栏 -->
      <Toolbar
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          style="border-bottom: 1px solid #ccc"
      />
      <!-- 编辑器 -->
      <el-input placeholder="请输入发布人" v-model="saveConsultationForm.username" ></el-input>
      <el-input placeholder="请输入标题" v-model="saveConsultationForm.title" ></el-input>
      <Editor
          v-model="valueHtml"
          :defaultConfig="editorConfig"
          @onChange="handleChange"
          @onCreated="handleCreated"
          @onDestroyed="handleDestroyed"
          @onFocus="handleFocus"
          @onBlur="handleBlur"
          @customAlert="customAlert"
          @customPaste="customPaste"
          style="height: 500px"
      />
    </div>
    <template #footer  >
      <el-button  type="primary" @click="save">确定</el-button>
      <el-button @click="handleClose">取消</el-button>
    </template>
  </el-dialog>

  <!-- 文章搜索卡片 -->
  <el-card style="margin: 20px;height: 80px;">
    <el-form :inline="true">
      <el-form-item label="标题" style="width: 220px;">
        <el-input placeholder="请输入标题" v-model="ConsultationForm.title" @keydown.enter="loadUser"></el-input>
      </el-form-item>
      <el-form-item label="发表人" style="width: 220px;">
        <el-input placeholder="请输入名称" v-model="ConsultationForm.username" @keydown.enter="loadUser"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadUser">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 用户表格卡片 -->
  <el-card style="margin: 20px;">
    <el-table :data="ConsultationArr">
      <el-table-column type="index" label="编号" width="80" align="center"></el-table-column>
      <el-table-column prop="title" label="标题" align="center"></el-table-column>
      <el-table-column prop="username" label="发布人" align="center"></el-table-column>
      <el-table-column prop="viewCount" label="浏览量" align="center"></el-table-column>
      <el-table-column prop="commentNum" label="评论量" align="center"></el-table-column>
      <el-table-column prop="likeNum" label="点赞数" align="center" ></el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="editUser(scope.row.id)" >编辑</el-button>
          <el-button link type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

</template>

<script setup>
import {onBeforeUnmount, onMounted, ref, shallowRef} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import axios from "axios";
import qs from "qs";
import {ElMessage} from "element-plus";

// 编辑器实例，必须用 shallowRef ，重要！
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p></p>')

// 编辑器配置
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: "http://localhost:8080/v1/file/upload",
      //文件名
      fieldName: "file",
      //上传方式
      methods: "post",
      //上传大小
      maxFileSize: 1 * 1024 * 1024,
      //文件限制
      allowedFileTypes: ['image/*'],
      onbeforeunload(file) {
        //超过大小后进行提示
        if (file.maxFileSize > 100 * 1024 * 1024) {
          //这里设置超过大小提示
          // $(".cover_inpput_label").text("文件大小超过限制，单个图片大小最多为10M").css("color", "red")
          return false;
        }
      }, onSuccess(file, res) {},
      customInsert(res, insertFn) {
        insertFn("http://localhost:8080" + res.data);
      },
      // 单个文件上传失败
      onFailed(file, res) {  },
      // 上传错误，或者触发 timeout 超时
      onError(file, err, res) {               // JS 语法

      }
    },
  }
}
// 编辑器回调函数
const handleCreated = (editor) => {
  console.log("created", editor);
  editorRef.value = editor // 记录 editor 实例，重要！
  // window.editor = editor // 临时测试使用，用完删除
}

const handleChange = (editor) => {
}
const handleDestroyed = (editor) => {
}
const handleFocus = (editor) => {
}
const handleBlur = (editor) => {
}
const customAlert = (info, type) => {
  alert(`【自定义提示】${type} - ${info}`)
}
const customPaste = (editor, event, callback) => {
  // 自定义插入内容// 禁止粘贴
  // editor.insertText('xxx')
  // 返回值（注意，vue 事件的返回值，不能用 return）
  callback(true) // 返回 false ，阻止默认粘贴行为
  // callback(true) // 返回 true ，继续默认的粘贴行为
}

// 及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return

  // 销毁，并移除 editor
  editor.destroy()
})

const toolbarConfig = {
  /* 工具栏配置 */
  toolbarKeys: [
    'clearStyle',
    'color',
    'bold',
    'bgColor',
    'underline',
    'through',
    'fontSize',
    'fontFamily',
    'lineHeight',

    '|',

    // 菜单组，包含多个菜单
    {
      key: 'group-image', // 必填，要以 group 开头
      title: '图片', // 必填
      // iconSvg: '<svg></svg>',
      menuKeys: [
        'uploadImage',
      ]
    },
    {
      key: 'group-link',
      title: '链接',
      menuKeys: ['insertLink', 'editLink', 'unLink', 'viewLink']
    },
    {
      key: 'group-table',
      title: '表格',
      menuKeys: ['insertTable',
        'deleteTable',
        'insertTableRow',
        'deleteTableRow',
        'insertTableCol',
        'deleteTableCol',
        'tableHeader',
        'tableFullWidth']
    },
    'divider',
    'emotion',
    'blockquote',
    'headerSelect',
    'redo',
    'undo',
    'fullScreen'
  ]
}

//定义变量控制弹窗是否出现
const dialogVisible = ref(false);
// //定义变量用来控制弹窗的标题
const dialogTitle = ref('添加文章');

const ConsultationForm = ref({
  title: '',
  username: '',
})

const saveConsultationForm=ref({
  username:'',
  title: '',
  content: '',
})

const ConsultationArr = ref([]);
const beforeAddUser = () => {
  dialogVisible.value = true;
  dialogTitle.value = '添加文章';
  saveConsultationForm.value = { };

  loadUser();
}
//定义加载文章的方法
const loadUser = () => {
  let data = qs.stringify(ConsultationForm.value);
  axios.get(BASE_URL + '/v1/healthcounse/select?' + data).then((response) => {
    if (response.data.code == 2000) {
      ConsultationArr.value = response.data.data;
      console.log(ConsultationArr);
    } else {
      ElMessage(response.data.msg);
    }
  })
}
onMounted(() => {
  loadUser();
})
//定义重置搜索条件的方法
const resetSearch = () => {
  //清空之前的搜索条件
  ConsultationForm.value = {};
  //重新加载所有的文章数据
  loadUser();
}
//定义插入文章的方法
const save = () => {
  saveConsultationForm.value.content=valueHtml.value;
  let data = qs.stringify(saveConsultationForm.value);
  console.log(data);
  axios.post(BASE_URL + '/v1/healthcounse/save', data).then((response) => {
    if (response.data.code == 2000) {
      ElMessage.success('保存成功!');
      //保存成功后关闭弹窗
      dialogVisible.value = false;
      //保存成功后清空表单数据
     saveConsultationForm.value = { };
      valueHtml.value = '<p></p>';
      loadUser();
    }
  })
}

//处理弹窗关闭的方法
const handleClose = ()=>{
  if(confirm('您确认要关闭本窗口吗?')){
    //关闭弹窗,并清空双向绑定的表单数据
    dialogVisible.value = false;
    saveConsultationForm.value = {};
    valueHtml.value = '<p></p>';
    loadUser();
  }
}

const editUser=(id)=>{
  //出弹窗 + 修改弹窗标题
  dialogVisible.value = true;
  dialogTitle.value = '修改文章';
  //根据用户id查询当前用户的详细数据显示在弹窗表单中
  axios.get(BASE_URL+'/v1/healthcounse/select?id='+id).then((response)=>{
    if(response.data.code == 2000){
      //注意:后端返回的是List<UserVO>,所以查一条数据的话拿的是集合的第1个元素,data[0]等价list.get(0)
      saveConsultationForm.value = response.data.data[0];
      valueHtml.value = response.data.data[0].content;

    }else{
      ElMessage.error(response.data.msg);
    }
  })
}

const deleteUser = (id) => {
  if (confirm('您确认要删除该文章吗?')) {
    axios.post(BASE_URL + '/v1/healthcounse/delete/' + id).then((response) => {
      if (response.data.code == 2000) {
        ElMessage.success('删除成功!');
        loadUser();
      } else {
        ElMessage.error(response.data.msg);
      }
    })
  }
}
</script>


<style src="@wangeditor/editor/dist/css/style.css">


</style>
